<template>
  <div class="cooperation-applications-view">
    <div class="page-header">
      <h1>合作申请管理</h1>
      <p>管理用户提交的合作申请信息</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名/电话">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入申请人姓名或电话"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>

        <el-form-item label="申请状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待处理" value="pending" />
            <el-option label="已联系" value="contacted" />
            <el-option label="已接受" value="accepted" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>

        <el-form-item label="合作意向">
          <el-select
            v-model="searchForm.intention"
            placeholder="请选择合作意向"
            clearable
            style="width: 150px"
          >
            <el-option label="区域代理" value="区域代理" />
            <el-option label="加盟合作" value="加盟合作" />
            <el-option label="分销合作" value="分销合作" />
            <el-option label="其他合作" value="其他合作" />
          </el-select>
        </el-form-item>

        <el-form-item label="申请时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-number">{{ stats.total || 0 }}</div>
          <div class="stat-label">总申请数</div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-number">{{ stats.today || 0 }}</div>
          <div class="stat-label">今日申请</div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-number">{{ stats.pending || 0 }}</div>
          <div class="stat-label">待处理</div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-number">{{ (stats.statusStats && stats.statusStats.accepted) || 0 }}</div>
          <div class="stat-label">已接受</div>
        </div>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        :data="applications"
        :loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        
        <el-table-column prop="name" label="申请人" width="120">
          <template #default="scope">
            <div class="user-info">
              <div class="user-name">{{ scope.row.name }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="联系电话" width="130">
          <template #default="scope">
            <el-button 
              type="text" 
              @click="callPhone(scope.row.phone)"
              class="phone-link"
            >
              {{ scope.row.phone }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column prop="intention" label="合作意向" width="120">
          <template #default="scope">
            <el-tag
              :type="getIntentionTagType(scope.row.intention)"
              size="small"
            >
              {{ scope.row.intention }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="详细说明" min-width="200">
          <template #default="scope">
            <el-tooltip
              v-if="scope.row.description && scope.row.description.length > 30"
              :content="scope.row.description"
              placement="top"
            >
              <div class="description-text">
                {{ scope.row.description.substring(0, 30) + '...' }}
              </div>
            </el-tooltip>
            <div v-else class="description-text">
              {{ scope.row.description || '无' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag
              :type="getStatusTagType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="申请时间" width="180" sortable="custom">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(scope.row)"
            >
              查看
            </el-button>
            <el-dropdown 
              @command="(command) => handleStatusAction(command, scope.row)"
              style="margin-left: 8px"
            >
              <el-button type="success" size="small">
                状态操作 <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="contacted" :disabled="scope.row.status === 'contacted'">
                    标记已联系
                  </el-dropdown-item>
                  <el-dropdown-item command="accepted" :disabled="scope.row.status === 'accepted'">
                    接受申请
                  </el-dropdown-item>
                  <el-dropdown-item command="rejected" :disabled="scope.row.status === 'rejected'">
                    拒绝申请
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <span style="color: #f56c6c">删除申请</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentApplication" class="application-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请人">
            {{ currentApplication.name }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <el-button type="text" @click="callPhone(currentApplication.phone)" class="phone-link">
              {{ currentApplication.phone }}
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="合作意向">
            <el-tag :type="getIntentionTagType(currentApplication.intention)" size="small">
              {{ currentApplication.intention }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getStatusTagType(currentApplication.status)" size="small">
              {{ getStatusText(currentApplication.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间" :span="2">
            {{ formatDate(currentApplication.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentApplication.updated_at && currentApplication.updated_at !== currentApplication.created_at" label="更新时间" :span="2">
            {{ formatDate(currentApplication.updated_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="详细说明" :span="2">
            <div class="description-content">
              {{ currentApplication.description || '无详细说明' }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentApplication.remark" label="管理员备注" :span="2">
            <div class="remark-content">
              {{ currentApplication.remark }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 状态操作对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      :title="statusDialogTitle"
      width="500px"
    >
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="备注">
          <el-input
            v-model="statusForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理备注（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStatusChange" :loading="statusLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import axios from '@/utils/request'

// 响应式数据
const loading = ref(false)
const applications = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const stats = ref({})

// 搜索表单
const searchForm = ref({
  search: '',
  status: '',
  intention: '',
})

const dateRange = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentApplication = ref(null)

// 状态操作对话框
const statusDialogVisible = ref(false)
const statusDialogTitle = ref('')
const statusLoading = ref(false)
const statusForm = ref({
  remark: ''
})
const pendingStatusChange = ref({
  id: null,
  status: '',
  action: ''
})

// 计算属性
const searchParams = computed(() => {
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    search: searchForm.value.search,
    status: searchForm.value.status,
    intention: searchForm.value.intention,
  }

  if (dateRange.value && dateRange.value.length === 2) {
    params.start_date = dateRange.value[0]
    params.end_date = dateRange.value[1]
  }

  return params
})

// 监听搜索参数变化
watch(searchParams, () => {
  if (currentPage.value === 1) {
    loadApplications()
  } else {
    currentPage.value = 1
  }
}, { deep: true })

// 生命周期
onMounted(() => {
  loadApplications()
  loadStats()
})

// 方法
const loadApplications = async () => {
  try {
    loading.value = true
    const response = await axios.get('/cooperation-applications', {
      params: searchParams.value
    })
    
    applications.value = response.data.applications || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('加载合作申请列表失败:', error)
    ElMessage.error('加载申请列表失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await axios.get('/cooperation-applications/stats/summary')
    stats.value = response.data || {}
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadApplications()
}

const handleReset = () => {
  searchForm.value = {
    search: '',
    status: '',
    intention: '',
  }
  dateRange.value = []
  currentPage.value = 1
  loadApplications()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadApplications()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadApplications()
}

const handleSortChange = ({ column, prop, order }) => {
  // 实现排序逻辑
  loadApplications()
}

const handleViewDetail = (application) => {
  currentApplication.value = application
  detailDialogVisible.value = true
}

const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentApplication.value = null
}

const handleStatusAction = (command, application) => {
  if (command === 'delete') {
    handleDeleteApplication(application)
    return
  }

  pendingStatusChange.value = {
    id: application.id,
    status: command,
    action: command
  }

  const titles = {
    contacted: '标记已联系',
    accepted: '接受申请',
    rejected: '拒绝申请'
  }

  statusDialogTitle.value = titles[command] || '状态变更'
  statusForm.value.remark = ''
  statusDialogVisible.value = true
}

const confirmStatusChange = async () => {
  try {
    statusLoading.value = true
    
    await axios.put(`/cooperation-applications/${pendingStatusChange.value.id}/status`, {
      status: pendingStatusChange.value.status,
      remark: statusForm.value.remark
    })

    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    loadApplications()
    loadStats()
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
  } finally {
    statusLoading.value = false
  }
}

const handleDeleteApplication = async (application) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除申请人"${application.name}"的合作申请吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    await axios.delete(`/cooperation-applications/${application.id}`)
    ElMessage.success('删除成功')
    loadApplications()
    loadStats()
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除申请失败:', error)
    ElMessage.error('删除失败')
  }
}

const callPhone = (phone) => {
  if (!phone) return
  window.location.href = `tel:${phone}`
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    contacted: '已联系',
    accepted: '已接受',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    contacted: 'primary',
    accepted: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

const getIntentionTagType = (intention) => {
  const typeMap = {
    '区域代理': 'success',
    '加盟合作': 'primary',
    '分销合作': 'warning',
    '其他合作': 'info'
  }
  return typeMap[intention] || 'info'
}
</script>

<style scoped>
.cooperation-applications-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-row {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  text-align: center;
  min-height: 80px;
}

.stat-content {
  padding: 10px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.phone-link {
  padding: 0;
  height: auto;
  font-size: 14px;
}

.description-text {
  line-height: 1.4;
  word-break: break-word;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.application-detail {
  padding: 10px 0;
}

.description-content,
.remark-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

.dialog-footer {
  text-align: center;
}
</style>